/*
 *              Copyright (C) 2011 The MusicMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *            http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.musicmod.plugin.socialize.weibo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;

public class MetaChangedReceiver extends BroadcastReceiver {

	private OAuthConsumer mConsumer;

	private String artist = Constants.DEFAULT_LATEST_ARTIST;
	private String album = Constants.DEFAULT_LATEST_ALBUM;
	private String track = Constants.DEFAULT_LATEST_TRACK;
	private String status;
	private boolean enabled;
	private long interval_milliseconds;
	private long curr_milliseconds;
	private long next_milliseconds;
	Date date;

	@Override
	public void onReceive(Context context, Intent intent) {

		enabled = SharedPrefsUtils.getBooleanPreference(context,
				Constants.KEY_ENABLE, false);

		if (!enabled) {
			return;
		}

		date = new Date();

		interval_milliseconds = Long.valueOf(SharedPrefsUtils
				.getStringPreference(context, Constants.KEY_POSTING_INTERVAL,
						Constants.DEFAULT_POSTING_INTERVAL)) * 1000;

		curr_milliseconds = date.getTime();

		try {
			Bundle bundle = intent.getExtras();
			artist = bundle.getString("artist");
			track = bundle.getString("track");
			album = bundle.getString("album");

			SharedPrefsUtils.setStringPreference(context,
					Constants.KEY_LATEST_ARTIST, artist);
			SharedPrefsUtils.setStringPreference(context,
					Constants.KEY_LATEST_ALBUM, album);
			SharedPrefsUtils.setStringPreference(context,
					Constants.KEY_LATEST_TRACK, track);

			String format = SharedPrefsUtils.getStringPreference(context,
					Constants.KEY_STATUS_FORMAT, context.getResources()
							.getString(R.string.status_format_default));

			next_milliseconds = SharedPrefsUtils.getLongPreference(context,
					Constants.KEY_NEXT_MILLISECONDS, 0);

			if (curr_milliseconds > next_milliseconds) {
				next_milliseconds = curr_milliseconds + interval_milliseconds;
				status = format.replaceAll("\\$\\{artist\\}", artist)
						.replaceAll("\\$\\{album\\}", album)
						.replaceAll("\\$\\{track\\}", track);

				if (networkSatisfied(context)) {
					sendStatus(context, cutStatus(context, status));
				}

				SharedPrefsUtils.setLongPreference(context,
						Constants.KEY_NEXT_MILLISECONDS, next_milliseconds);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean networkSatisfied(Context context) {
		ConnectivityManager mConnectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivity.getActiveNetworkInfo();

		if (mNetworkInfo == null || !mConnectivity.getBackgroundDataSetting()) {
			return false;
		}

		boolean post_wifi = SharedPrefsUtils.getBooleanPreference(context,
				Constants.KEY_POST_WIFI, true);

		int mNetworkType = mNetworkInfo.getType();

		if (mNetworkType == ConnectivityManager.TYPE_WIFI) {
			return mNetworkInfo.isConnected();
		} else if (mNetworkType == ConnectivityManager.TYPE_MOBILE) {
			if (post_wifi) {
				return false;
			} else {
				return mNetworkInfo.isConnected();
			}
		} else {
			return false;
		}
	}

	private String cutStatus(Context context, String orig) {
		String string = orig.trim();
		StringBuilder builder = new StringBuilder();
		if (string.length() > Constants.MAX_STATUS_LENGTH) {
			return builder
					.append(string
							.substring(0, Constants.MAX_STATUS_LENGTH - 5))
					.append(context.getResources().getString(R.string.ellipsis))
					.toString();
		} else {
			return string;
		}
	}

	/**
	 * set status
	 * 
	 * @param context
	 * @param status
	 */
	private void sendStatus(final Context context, final String status) {

		Thread thread = new Thread() {
			public void run() {
				try {
					mConsumer = new CommonsHttpOAuthConsumer(
							Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);

					String access_token = SharedPrefsUtils.getStringPreference(
							context, Constants.KEY_ACCESS_TOKEN,
							Constants.DEFAULT_ACCESS_TOKEN);
					String token_secret = SharedPrefsUtils.getStringPreference(
							context, Constants.KEY_TOKEN_SECRET,
							Constants.DEFAULT_TOKEN_SECRET);

					mConsumer.setTokenWithSecret(access_token, token_secret);

					HttpPost request = new HttpPost(
							Constants.STATUSES_UPDATE_ENDPOINT);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("status", status));
					request.setEntity(new UrlEncodedFormEntity(params,
							HTTP.UTF_8));

					mConsumer.sign(request);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = client.execute(request);
					Log.d(Constants.LOG_TAG,
							"Send status. response: "
									+ String.valueOf(response.getStatusLine()));
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		};
		thread.start();
	}
}